//
//  AfterWebViewController.m
//  LoanMoney
//
//  Created by gynjobs on 2017/8/29.
//  Copyright © 2017年 cangming. All rights reserved.
//

#import "AfterWebViewController.h"
#import "HDDeviceInfoUploadHelper.h"
#import "RBRefreshHeader.h"
#import <ImageIO/ImageIO.h>
#import <AdSupport/AdSupport.h>
@interface AfterWebViewController ()<UIWebViewDelegate>{
    UIImageView *loadingView;
    RBRefreshHeader *header;
}
@property(strong,nonatomic)UIWebView *webView;
@end

@implementation AfterWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    self.webView = [[UIWebView alloc]init];
    self.webView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.webView];
    self.webView.frame = CGRectMake(0, 0, WINSIZEWIDTH, WINSIZEHEIGHT);
//    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.view.mas_left);
//        make.right.equalTo(self.view.mas_right);
//        make.top.equalTo(self.view.mas_top);
//        make.bottom.equalTo(self.view.mas_bottom);
//    }];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
    self.webView.delegate = self;
    
    __weak typeof(self) weakself = self;
    header = [RBRefreshHeader headerWithRefreshingBlock:^{
        //[weakself headerReload];
        //[weakself.myWebView loadRequest:currentRequest];
        [weakself.webView reload];
    }];
    header.frame = CGRectMake(0, -header.frame.size.height, kWidth, header.frame.size.height);
    [self.webView.scrollView addSubview:header];
    [self.view addSubview:[self getLoadingView]];

    // Do any additional setup after loading the view.
}
- (void)viewWillDisappear:(BOOL)animated{
    [header removeFromSuperview];
    header = nil;
    [super viewWillDisappear:animated];
    if (self.isHiddenTabbar==YES) {
        BaseCommondTabbarController *tabbar = (BaseCommondTabbarController *)self.tabBarController;
        [tabbar HiddenTheTabbar:NO];
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.isHiddenTabbar==YES) {
        BaseCommondTabbarController *tabbar = (BaseCommondTabbarController *)self.tabBarController;
        [tabbar HiddenTheTabbar:YES];
    }
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    [self.view addSubview:[self getLoadingView]];
    if (self.isCon) {
        [self addLeftBackButton];
    }
    //    if ([NSString isBlankStringWithString:[webView.request.URL absoluteString]]) {
    //        return;
    //    }
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [LoadingAnimalView hideLoadingForView:self.view];
    [loadingView removeFromSuperview];
    if ([[webView.request.URL absoluteString] isEqualToString:self.webUrl]) {
        [self setNoneLeftButton];
    }else{
        [self addLeftBackButton];
    }
    loadingView = nil;
    if ([NSString isBlankStringWithString:self.controllerString]) {
        self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }else{
        self.title = self.controllerString;
    }
    
    [header endRefreshing];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [LoadingAnimalView hideLoadingForView:self.view];
    [header endRefreshing];
    [loadingView removeFromSuperview];
    loadingView = nil;
    GYNLog(@"load page error:%@", [error description]);
}

-(void)addLeftBackButton{
    UIImageView *backButton = [self setLeftNavigationButtonIconName:@"返回icon" AndSize:CGSizeMake(40, 60)];
    backButton.contentMode = UIViewContentModeCenter ;
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(skidClick:)];
    [backButton addGestureRecognizer:tapGes];
}
-(void)setNoneLeftButton{
    self.navigationItem.leftBarButtonItem = nil;
}
-(void)skidClick:(UITapGestureRecognizer *)tapGes{
    if (self.isCon) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self setNoneLeftButton];
    }
}

- (UIImageView *)getLoadingView{
    if (!loadingView) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"loading2" ofType:@"gif"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        loadingView = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth/2.0-35, kHeight/2.0-35-70, 70, 70)];
        loadingView.image = [AfterWebViewController sd_animatedGIFWithData:data];
    }
    return loadingView;
}
+ (UIImage *)sd_animatedGIFWithData:(NSData *)data {
    if (!data) {
        return nil;
    }
    
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
    
    size_t count = CGImageSourceGetCount(source);
    
    UIImage *animatedImage;
    
    if (count <= 1) {
        animatedImage = [[UIImage alloc] initWithData:data];
    }
    else {
        NSMutableArray *images = [NSMutableArray array];
        
        NSTimeInterval duration = 0.0f;
        
        for (size_t i = 0; i < count; i++) {
            CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);
            
            duration += [self sd_frameDurationAtIndex:i source:source];
            
            [images addObject:[UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
            
            CGImageRelease(image);
        }
        
        if (!duration) {
            duration = (1.0f / 10.0f) * count;
        }
        
        animatedImage = [UIImage animatedImageWithImages:images duration:duration];
    }
    
    CFRelease(source);
    
    return animatedImage;
}

+ (float)sd_frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
    float frameDuration = 0.1f;
    CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;
    NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];
    
    NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    if (delayTimeUnclampedProp) {
        frameDuration = [delayTimeUnclampedProp floatValue];
    }
    else {
        
        NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];
        if (delayTimeProp) {
            frameDuration = [delayTimeProp floatValue];
        }
    }
    
    // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
    // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
    // a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>
    // for more information.
    
    if (frameDuration < 0.011f) {
        frameDuration = 0.100f;
    }
    
    CFRelease(cfFrameProperties);
    return frameDuration;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
